package com.ruoyi.crm.service.impl;

import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.crm.domain.*;
import com.ruoyi.crm.domain.vo.ContractVo;
import com.ruoyi.crm.domain.vo.GivBackVo;
import com.ruoyi.crm.mapper.ActivityMapper;
import com.ruoyi.crm.mapper.ContractMapper;
import com.ruoyi.crm.mapper.CourseMapper;
import com.ruoyi.crm.service.IAssignRecordService;
import com.ruoyi.modules.mq.CrmMqProducer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.ruoyi.crm.mapper.BusinessMapper;
import com.ruoyi.crm.service.IBusinessService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 商机Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-03-16
 */
@Service
public class BusinessServiceImpl implements IBusinessService 
{
    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private IAssignRecordService assignRecordService;
    @Resource
    private ContractMapper contractMapper;
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private CrmMqProducer crmMqProducer;

    /**
     * 查询商机
     * 
     * @param id 商机主键
     * @return 商机
     */
    @Override
    public Business selectBusinessById(Long id)
    {
        return businessMapper.selectBusinessById(id);
    }

    /**
     * 查询商机列表
     * 
     * @param business 商机
     * @return 商机
     */
    @Override
    public List<Business> selectBusinessList(Business business)
    {
        return businessMapper.selectBusinessList(business);
    }

    /**
     * 新增商机
     * 
     * @param business 商机
     * @return 结果
     */
    @Override
    public int insertBusiness(Business business)
    {
        business.setCreateBy(SecurityUtils.getUsername());
        business.setCreateTime(DateUtils.getNowDate());
        return businessMapper.insertBusiness(business);
    }

    /**
     * 修改商机
     * 
     * @param business 商机
     * @return 结果
     */
    @Override
    public int updateBusiness(Business business)
    {
        business.setUpdateTime(DateUtils.getNowDate());
        business.setUpdateBy(SecurityUtils.getUsername());
        return businessMapper.updateBusiness(business);
    }

    /**
     * 批量删除商机
     * 
     * @param ids 需要删除的商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessByIds(Long[] ids)
    {
        return businessMapper.deleteBusinessByIds(ids);
    }

    /**
     * 删除商机信息
     * 
     * @param id 商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessById(Long id)
    {
        return businessMapper.deleteBusinessById(id);
    }

    @Override
    @Transactional
    public int givBack(GivBackVo givBackVo) {
        AssignRecord assignRecord = new AssignRecord();
        assignRecord.setId(givBackVo.getId());
        assignRecord.setType(AssignRecord.Type.BUSINESS.getValue());
        assignRecord.setLatest("0");
        assignRecordService.updateAssignRecord(assignRecord);
        Business business=businessMapper.selectBusinessById(givBackVo.getId());
        business.setStatus(Clue.Status.FAKE.getValue());
        return businessMapper.updateBusiness(business);
    }

    @Override
    public int reset(Long id) {
        //分配商机给当前用户
        AssignRecord assignRecord=new AssignRecord();
        assignRecord.setType(AssignRecord.Type.BUSINESS.name());
        assignRecord.setAssignId(id);
        assignRecord.setUserId(SecurityUtils.getUserId());
        assignRecord.setDeptId(SecurityUtils.getDeptId());
        assignRecord.setCreateTime(DateUtils.getNowDate());
        assignRecord.setUserName(SecurityUtils.getUsername());
        return assignRecordService.insertAssignRecord(assignRecord);
    }

    //转商机
    @Override
    @Transactional
    public int turnClient(ContractVo contractVo) {
        //更新商机状态
        Business business=businessMapper.selectBusinessById(contractVo.getId());
        if(business.getCourseId()==null){
            throw new RuntimeException("商机里面没有选择课程，无法转换客户合同");
        }
        if(contractMapper.selectContractByNo(contractVo.getContractNo())>0){
            throw new RuntimeException("合同编号已经存在，无法转换客户合同");
        }
        business.setStatus(Clue.Status.TO_CUSTOMER.getValue());
        business.setUpdateBy(SecurityUtils.getUsername());
        business.setUpdateTime(new Date());
        businessMapper.updateBusiness(business);
        //插入合同，对合同表进行新增
        Contract contract=new Contract();
        BeanUtils.copyProperties(business,contract);
        contract.setId(Seq.getId());
        contract.setContractNo(contractVo.getContractNo());
        contract.setFileName(contractVo.getFileName());
        contract.setPhone(contractVo.getPhone());
        contract.setEmail(contractVo.getMailbox());
        contract.setStatus("4");//状态(待审核1，已通过2，已驳回3，全部完成4)
        contract.setBusinessId(business.getId());
        contract.setCreateTime(new Date(System.currentTimeMillis()));
        contract.setCreateBy(SecurityUtils.getUsername());
        contract.setDeptId(SecurityUtils.getDeptId());
        //根据活动计算优惠后的金额
        setContractOrder(contract);
        contractMapper.insertContract(contract);
        //通过邮件和短信发送序列号给用户
        crmMqProducer.produceContractCreateMessage(contract);
        return 1;
    }

    private void setContractOrder(Contract contract) {
        Course course=courseMapper.selectCourseById(contract.getCourseId());
        Activity activity=null;
        if(contract.getActivityId()!=null){
            activity=activityMapper.selectActivityById(contract.getCourseId());
        }
        if(activity==null){
            contract.setContractOrder(Double.valueOf(course.getPrice()));
        }else {
            if("1".equals(activity.getType())){
                contract.setDiscountType("课程折扣");
                contract.setContractOrder((activity.getDiscount() / 10.00 * course.getPrice()));
            }else {
                contract.setDiscountType("代金券");
                contract.setContractOrder((double) (course.getPrice()-activity.getVouchers()));
            }
        }
    }
}
